package com.sinopec.basemodule.widget.wxbookview

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.R
import com.sinopec.basemodule.utils.NetUtil

/**
 * 创建人：lwj<br/>
 * 创建时间：2019/11/20 09:46 <br/>
 */
abstract class WXBaseAdapter<T : WXBean>(@LayoutRes private val layoutId: Int, val list: MutableList<T>?) :
        RecyclerView.Adapter<WXViewHolder>() {
    companion object {
        const val EMPTY_VIEW = -10000
    }

    init {
        //初始化Pinyin字段 并且排序
        list?.let {
            WXUtils.sort(list)
        }
    }

    override fun getItemViewType(position: Int): Int {
        val count = list?.size ?: 0
        if (count == 0) {
            return EMPTY_VIEW
        }
        return count
    }

    override fun getItemCount(): Int {
        return list?.size ?: 0
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WXViewHolder {
        val view = if (viewType == EMPTY_VIEW) {
            //无数据样式
            LayoutInflater.from(parent.context).inflate(R.layout.view_empty, parent, false)
        } else {
            LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        }
        return WXViewHolder(view)
    }

    override fun onBindViewHolder(holder: WXViewHolder, position: Int) {
        if (getItemViewType(position) == EMPTY_VIEW) {
            bingEmptyViewHolder(holder)
        } else {
            bindViewHolder(holder, position, list!![position])
        }
    }

    /**
     * 绑定数据
     */
    abstract fun bindViewHolder(holder: WXViewHolder, position: Int, model: T)

    /**
     * 无数据样式
     */
    private fun bingEmptyViewHolder(holder: WXViewHolder) {
        val imageView = holder.getView<ImageView>(R.id.imageView)
        if (NetUtil.isNetworkAvailable(BaseApplication.getInstance())) {
            imageView.setImageResource(R.drawable.no_data_img)
        } else {
            imageView.setImageResource(R.drawable.no_net_img)
        }
    }

    override fun onBindViewHolder(holder: WXViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        }else{
            if (getItemViewType(position) == EMPTY_VIEW) {
                bingEmptyViewHolder(holder)
            } else {
                bindViewHolder(holder, position, list!![position], payloads)
            }
        }
    }

    open fun bindViewHolder(holder: WXViewHolder, position: Int, model: T, payloads: MutableList<Any>) {

    }
}